package hu.fic.weddingstorefinder.utils;

import hu.fic.weddingstorefinder.db.WeddingStoreDBAdapter;
import hu.fic.weddingstorefinder.db.table.Dress;
import hu.fic.weddingstorefinder.db.table.POI;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class JSONProcessor extends AsyncTask<String, Integer, Boolean>{
	
	private Activity activityForDB;
	private int jsonType;
	private JSONProcessorListener jsonProcessorListener;
	private String errorMessage;
	private static final String LOG_TAG = "JSONProcessor";
	
	public JSONProcessor (int jsonType, Activity activityForDB, JSONProcessorListener jsonProcessorListener) {
		this.activityForDB = activityForDB;
		this.jsonType = jsonType;
		this.jsonProcessorListener = jsonProcessorListener;
	}
	
	@Override
	protected Boolean doInBackground(String... params) {
		// TODO Auto-generated method stub
		try {
			String jsonString = params[0];
			JSONObject jsonObject = new JSONObject(jsonString);
			JSONArray responseArr = jsonObject.optJSONArray(Constants.JSON_RESPONSE);
			if (jsonType == Constants.JSONTYPE_POI) {
				POI poi = new POI(WeddingStoreDBAdapter.getInstance().getDb(), activityForDB);
				poi.processPoiListFromJSON(responseArr);
			} else if (jsonType == Constants.JSONTYPE_DRESS) {
				Dress dress = new Dress(WeddingStoreDBAdapter.getInstance().getDb(), activityForDB);
				dress.processDressListFromJSON(responseArr);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			errorMessage = "JSONProcess error: " + e.getMessage();
			return new Boolean(false);
		}
		return new Boolean(true);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (result.booleanValue()) {
			jsonProcessorListener.jsonProcessDone();
		} else {
			jsonProcessorListener.jsonProcessFailed(this.errorMessage);
		}
	}

}
